package com.heima.behavior.service.impl;

import com.heima.behavior.config.CacheService;
import com.heima.behavior.service.ApUnLikesBehaviorService;
import com.heima.common.constants.user.UserRelationConstants;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApUnLikesBehaviorServiceImpl implements ApUnLikesBehaviorService {
    @Autowired
    CacheService cacheService;

    /**
     * 不喜欢
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult unLike(UnLikesBehaviorDto dto) {
        //参数校验
        if (dto == null || dto.getArticleId() == null || dto.getType() > 2 || dto.getType() < 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取登录人信息
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null) {
            return ResponseResult.okResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //保存不喜欢数据
        if (dto.getType() == 0) {
            Double score = cacheService.zScore(UserRelationConstants.UNLIKE_LIST + apUser.getId(), dto.getArticleId().toString());
            if (score != null) {
                CustException.cust("您已选择不喜欢,请勿重复选择");
            }
            //保存
            cacheService.zAdd(UserRelationConstants.UNLIKE_LIST + apUser.getId(), dto.getArticleId().toString(), System.currentTimeMillis());

        } else {
            //取消不喜欢
            cacheService.zRemove(UserRelationConstants.UNLIKE_LIST + apUser.getId(), dto.getArticleId().toString());
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
